import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom"
import { getRoutes } from "@/router/config"
import { IsHashRouter } from "@/config"
import { LazyExoticComponent, JSX, useEffect, useState } from "react"
import { SuspenseLoading } from "@/components/Loading"
import NiceModal from "@ebay/nice-modal-react"

const Router = IsHashRouter ? HashRouter : BrowserRouter

export const AppRouter = (): JSX.Element => {
    const [routesData, setRoutesData] = useState<any[]>([])

    function loadRoutes() {
        setRoutesData(getRoutes())
    }

    useEffect(() => {
        loadRoutes()
    }, [])

    return (
        <NiceModal.Provider>
            <Router>
                <Routes>
                    {routesData.map(route => {
                        if (typeof route.component === "object") {
                            const Component = route.component as LazyExoticComponent<() => JSX.Element>
                            return (
                                <Route
                                    path={route.path}
                                    key={route.name}
                                    element={<SuspenseLoading>{<Component></Component>}</SuspenseLoading>}
                                />
                            )
                        } else {
                            return (
                                <Route path={route.path} key={route.name} element={<route.component route={route} />} />
                            )
                        }
                    })}
                </Routes>
            </Router>
        </NiceModal.Provider>
    )
}
